import { getRootWindow } from '@src/util/dom';
import { translateLanguage } from 'pub-bbx-global/lang/dist/utils/languageList'
import { lastCoverLanguage } from 'pub-bbx-global/lang/dist/utils/config'
import { LanguageItem } from 'pub-bbx-global/lang/dist/token'
import { GrayFunctionEnum } from 'pub-bbx-global/pageType/dist/grayFunction'
import { transformI18n } from '@src/locales'
import { cloneDeep } from 'lodash'; 

const defaultLanguages = translateLanguage;

// 是否开启ToC多语灰度
export function getOpenMultiLanguage() {
  const RootWindow = getRootWindow(window);
  return !!RootWindow.grayAuth?.multiLanguage;
}

// 语言列表
export function getLanguagesList(isInit = false) {
  const RootWindow = getRootWindow(window);
  return RootWindow?.languages ?? defaultLanguages
}

export function getMainLanguageKey(){
  const list = getLanguagesList();
  let mainLa = list.find((item:LanguageItem)=>item.isMainLanguage);
  return mainLa.languageKey || lastCoverLanguage
}


export function useFormMultiLanguage() {
  const isOpenMultiLanguage = getOpenMultiLanguage();
  let languagesList = [...getLanguagesList()];
  const RootWindow = getRootWindow(window);
  
  if (!isOpenMultiLanguage) {
    // 不支持多语言保留一个
    languagesList = languagesList.filter(item=>item.isMainLanguage);
  }
  return {
    isOpenMultiLanguage,
    languagesList,
    internationalGray: RootWindow?.grayAuth?.[GrayFunctionEnum.INTERNATIONAL] ?? false, // 国际化灰度
  };
}



export const deepTranslateByKey:any = (translate: string | any | Array<any>, la:string) => {
  try {
    let data = cloneDeep(translate);
    if(typeof data === 'string'){
      if (data) {
        // 不是国际化翻译参数
        if(!data.includes('.')) return data;
        return transformI18n(`${data}`, la) || '';
      } else {
        return '';
      }
    }else if(typeof data === 'object'){
      for(let key in data){
        data[key] = deepTranslateByKey(data[key], la);
      }
      return data;
    }
  } catch (error) {
    console.warn(error, 'error try catch deepTranslateByKey');
  }
}

/**
* @des 根据key初始化language对象
*/
export function getCommonDefaultLangForKey(data?: string | any | Array<any>) {
  const language = getLanguagesList();
  const obj: Record<string, any> = {};
  language.forEach((item: LanguageItem) => {
    obj[item.languageKey] = deepTranslateByKey(data, item.languageKey);
  });
  return obj;
}

export default useFormMultiLanguage;
